package logic

import (
	"errors"
	"math/rand"
	"strconv"
	"zk507/common/dao"
	"zk507/common/models"
	"zk507/common/pkg"
	"zk507/common/proto/user"
)

func UserLogin(in *user.UserLoginRequest) (*user.UserLoginResponse, error) {
	code := dao.GetSms(in.Mobile)

	u := models.User{}
	err := u.GetUserMobileInfo(in.Mobile)
	if err != nil {
		return nil, errors.New("账号不存在，请先注册")
	}
	if in.Code != code {
		return nil, errors.New("验证码输入错误,请重新输入")
	}
	err = dao.DelSms(in.Mobile)
	if err != nil {
		return nil, errors.New("验证码销毁失败")
	}
	return &user.UserLoginResponse{UserId: int64(u.ID)}, nil
}

func Sms(in *user.SmsRequest) (*user.SmsResponse, error) {
	code := strconv.Itoa(rand.Intn(9000) + 1000)
	sms, _ := pkg.Sms(in.Mobile, code)
	if *sms.Body.Code != "OK" {
		return nil, errors.New(*sms.Body.Message)
	}

	err := dao.SetSms(in.Mobile, in.Source, code)
	if err != nil {
		return nil, errors.New("验证码缓存失败")
	}
	return &user.SmsResponse{Success: true}, nil
}

func InformationSynchronous(in *user.InformationSynchronousRequest) (*user.InformationSynchronousResponse, error) {
	u := models.Information{}
	list, err := u.GetList()
	if err != nil {
		return nil, errors.New("企业信息查询失败")
	}
	err = dao.Set(list)
	if err != nil {
		return nil, errors.New("企业信息存储redis失败")
	}
	return &user.InformationSynchronousResponse{Success: true}, nil
}

func InformationList(in *user.InformationListRequest) (*user.InformationListResponse, error) {
	u := models.Information{}
	list, err := u.GetFormationList(in.Address, in.Scale)
	if err != nil {
		return nil, errors.New("企业信息查询失败")
	}
	return &user.InformationListResponse{List: list}, nil
}
